package com.msos.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @ClassName: DBUtils
 * @Description: TODO
 * @Author: hsx
 * @Date: 2022/4/12 16:52
 * @Version: v1.0
 */
public class DBUtils {
    private static DataSource ds = null;
    private static final Properties PROPERTIES = new Properties();
    private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal<>();

    static {
        try {
            PROPERTIES.load(DBUtils.class.getResourceAsStream("/jdbc.properties"));
            ds = DruidDataSourceFactory.createDataSource(PROPERTIES);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getCon() {
        Connection connection = THREAD_LOCAL.get();
        if (connection == null) {
            try {
                connection = ds.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

    public static DataSource getDs() {
        return ds;
    }

    public static void close(Connection con) {
        if (con != null) {
            try {
                con.close();
                THREAD_LOCAL.remove();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(PreparedStatement ps) {
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
